package com.example.xmhds_1.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.baomidou.mybatisplus.extension.spring.MybatisSqlSessionFactoryBean;
import com.baomidou.mybatisplus.core.MybatisConfiguration;
import com.example.xmhds_1.config.handler.JSONArrayTypeHandler;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * 用户信息数据源配置
 * 用于访问 yuebi-1 数据库
 */
@Configuration
@MapperScan(basePackages = "com.example.xmhds_1.mapper.userinfo", sqlSessionTemplateRef = "userInfoSqlSessionTemplate")
public class UserInfoDataSourceConfig {

    @Value("${spring.datasource.user-info.url}")
    private String url;

    @Value("${spring.datasource.user-info.username}")
    private String username;

    @Value("${spring.datasource.user-info.password}")
    private String password;

    @Value("${spring.datasource.user-info.driver-class-name}")
    private String driverClassName;

    @Bean(name = "userInfoDataSource")
    public DataSource userInfoDataSource() {
        DruidDataSource dataSource = new DruidDataSource();
        dataSource.setUrl(url);
        dataSource.setUsername(username);
        dataSource.setPassword(password);
        dataSource.setDriverClassName(driverClassName);
        return dataSource;
    }

    @Bean(name = "userInfoSqlSessionFactory")
    public SqlSessionFactory userInfoSqlSessionFactory(@Qualifier("userInfoDataSource") DataSource dataSource) throws Exception {
        MybatisSqlSessionFactoryBean bean = new MybatisSqlSessionFactoryBean();
        bean.setDataSource(dataSource);

        // 使用 MyBatis-Plus 的配置类
        MybatisConfiguration configuration = new MybatisConfiguration();
        configuration.setMapUnderscoreToCamelCase(true);
        // 注册类型处理器
        configuration.getTypeHandlerRegistry().register(JSONArrayTypeHandler.class);
        bean.setConfiguration(configuration);

        return bean.getObject();
    }

    @Bean(name = "userInfoTransactionManager")
    public DataSourceTransactionManager userInfoTransactionManager(@Qualifier("userInfoDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    @Bean(name = "userInfoSqlSessionTemplate")
    public SqlSessionTemplate userInfoSqlSessionTemplate(@Qualifier("userInfoSqlSessionFactory") SqlSessionFactory sqlSessionFactory) {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
